/**
 *
 */
package com.newer.controller.auth;

import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 登录Controller
 *
 * @author 寻添俊
 * 2017年11月30日-下午1:12:14
 */
@Controller
public class LoginController {

    /**
     * 默认跳转页面
     *
     * @return
     */
    @RequestMapping("login.htm")
    public String login() {
        return "login";
    }

    /**
     * 登录操作
     *
     * @return
     */
    @RequestMapping(value = "login.do", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    @ResponseBody
    public String doLogin(@RequestParam(defaultValue = "false") boolean rememberMe, HttpSession session, @RequestParam String loginName, @RequestParam String loginPassword, ModelMap map) {
        JSONObject json = new JSONObject();
        // 用户登录
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginName, loginPassword,
                rememberMe);
        try {
            subject.login(token);
            json.put("success", true);
        } catch (AuthenticationException e) {
            // 其他错误，比如锁定，如果想单独处理请单独catch 处理
            e.printStackTrace();
            json.put("success", false);
            json.put("msg", "登录失败错误.");
        }
        return json.toString();
    }

    /**
     * 登出操作
     *
     * @return
     */
    @RequestMapping("logout.do")
    public String logout() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "login";
    }
}
